package cn.joyfulmedia.common.util.page;

import java.io.Serializable;

public class Pagination implements Serializable {

    /**
     * 默认每页数量：20
     */
    public static final int DEFAULT_PAGE_SIZE = 20;
    public static final int DEFAULT_CURRENT_PAGE = 1;
    public static final int MAX_PAGE_SIZE = 200;
    private static final long serialVersionUID = -5725617736450087533L;
    /**
     * 每页显示记录数
     */
    private int rows = DEFAULT_PAGE_SIZE;
    /**
     * 总条目数
     */
    private int total;
    /**
     * 总页数
     */
    private int totalPage;
    //
    /**
     * 当前页
     */
    private int page = DEFAULT_CURRENT_PAGE;
    /**
     * 当前记录起始索引
     */
    private int currentResult;
    /**
     * 排序字段
     */
    private String orderBy;

    public Pagination() {
        this(DEFAULT_PAGE_SIZE, DEFAULT_CURRENT_PAGE);
    }

    public Pagination(int rows) {
        this(rows, DEFAULT_CURRENT_PAGE);
    }

    public Pagination(int rows, int page) {
        this.rows = rows;
        this.setPage(page);
    }

    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    public int getRows() {
        if (this.rows > MAX_PAGE_SIZE) {
            this.rows = MAX_PAGE_SIZE;
        }
        return rows;
    }

    public void setRows(int rows) {
        if (rows > 20) {
            this.rows = 20;
        } else {
            this.rows = rows;
        }
        this.setPage(this.getPage());
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
        totalPage = total % rows == 0 ? total / rows : (total / rows + 1);

        updateCurrentResult();
    }

    public int getCurrentResult() {
        return currentResult;
    }

    public void setCurrentResult(int currentResult) {
        this.currentResult = currentResult;
    }

    public int getPage() {
        if (page <= 1) {
            return 1;
        }
        return page;
    }

    public void setPage(int page) {
        if (page < 1) {
            this.page = 1;
        } else {
            this.page = page;
        }
        updateCurrentResult();
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    // 更新当前开始索引
    private void updateCurrentResult() {
        this.currentResult = (this.getPage() - 1) * this.getRows();
    }

    @Override
    public String toString() {
        return "Pagination [rows=" + this.rows + ", total=" + this.total + ", totalPage=" + this.totalPage + ", page="
                + this.page + ", currentResult=" + this.currentResult + ", orderBy=" + this.orderBy + "]";
    }

}
